//
//  NYTopicListViewController.m
//  Nooryes
//
//  Created by baken on 2020/3/3.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYTopicListViewController.h"
#import "NYSearchViewController.h"
#import "NYTopicListTableViewCell.h"
#import "NYTopicViewModel.h"
#import "NYTopicListModel.h"
#import "NYTopicArticlesViewController.h"

@interface NYTopicListViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableview;

@property(nonatomic, strong) NYTopicViewModel *topicVM;
@end

@implementation NYTopicListViewController

-(NYTopicViewModel *)topicVM{
    if (!_topicVM) {
        _topicVM = [NYTopicViewModel new];
    }
    return _topicVM;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableview.rowHeight = kTopicRowHeight;
    self.tableview.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.topicVM refreshDataCompletionHandle:^(NSError *error) {
            [self.tableview reloadData];
            [self.tableview.mj_header endRefreshing];
        }];
    }];
    
    self.tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self.topicVM getMoreDataCompletionHandle:^(NSError *error) {
            [self.tableview reloadData];
            [self.tableview.mj_footer endRefreshing];
        }];
        
    }];
    
    [self.tableview.mj_header beginRefreshing];
    
    
}


#pragma mark UITableView
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicListModel *model = [self.topicVM.dataArr objectAtIndex:indexPath.row];
    NYTopicListTableViewCell *cell = [NYTopicListTableViewCell cellWithTableView:tableView];
    cell.model = model;
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    TopicListModel *model = [self.topicVM.dataArr objectAtIndex:indexPath.row];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"TopicStoryboard" bundle:nil];
    NYTopicArticlesViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYTopicArticlesViewController"];
    detailVC.topicID = model.talkid;
    [self.navigationController pushViewController:detailVC animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.topicVM.dataArr.count;
}


#pragma mark UISearchBar Delegate

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    NYSearchViewController *searchViewController = [[NYSearchViewController alloc] initWithNibName:@"NYSearchViewController" bundle:nil];
    [self.navigationController pushViewController:searchViewController animated:YES];
    
    return NO;
}

@end
